package cn.iocoder.yudao.module.ai.graph.node.customerservice;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送回复节点 - 将审核通过的回复发送给客户
 * 
 * @author yudao
 * @since 2025/10/17
 */
public class SendReplyNode implements NodeAction {

    private static final Logger logger = LoggerFactory.getLogger(SendReplyNode.class);

    @Override
    public Map<String, Object> apply(OverAllState state) {
        logger.info("=== SendReplyNode 开始执行 ===");
        
        String customerId = state.value("customer_id", "");
        String finalReply = state.value("final_reply", "");
        boolean humanApproved = state.value("human_approved", false);
        
        logger.info("客户 ID：{}", customerId);
        logger.info("最终回复：{}", finalReply);
        logger.info("人工审核：{}", humanApproved ? "已审核" : "未审核");
        
        // 模拟发送回复的过程
        try {
            // 这里可以集成实际的消息发送服务（微信、邮件、短信等）
            sendMessage(customerId, finalReply);
            
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("send_status", "success");
            resultMap.put("send_time", timestamp);
            
            logger.info("✓ 回复已成功发送给客户");
            
            return resultMap;
            
        } catch (Exception e) {
            logger.error("✗ 发送回复失败", e);
            
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("send_status", "failed");
            resultMap.put("error_message", e.getMessage());
            
            return resultMap;
        }
    }

    /**
     * 模拟发送消息
     */
    private void sendMessage(String customerId, String message) {
        // 实际项目中，这里应该调用消息服务
        logger.info("📤 [发送消息] 客户：{}, 内容：{}", customerId, message);
        
        // 模拟网络延迟
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

